const fs = require('fs')
const bip39 = require("bip39");
const bip32 = require("ripple-bip32");

/**
 *  随机生成一定数量的助记词，并写入 mnemonic.json 文件
 * @param num
 * @returns {[]}
 */
const generateMnemonicList = (num) => {
  const generateMnemonic = function() {
    return bip39.generateMnemonic()
  }
  const arr = []
  const list = new Array(num).fill(0)
  list.forEach(item => {
    arr.push({ mnemonic: generateMnemonic() })
  })
  try {
    fs.writeFileSync('./mnemonic.json', JSON.stringify(arr), 'utf-8')
  } catch (e) {
    console.log(e)
  }
}


/**
 *  通过助记词拿到私钥，公钥，地址
 * @param mnemonic
 * @returns {{privateKey: *, address: *, mnemonic: *, publicKey: *}}
 */
function generateAccountByMnemonic(mnemonic) {
  const seed = bip39.mnemonicToSeedSync(mnemonic)
  const m = bip32.fromSeedBuffer(seed)
  // const masterSeed = m.toBase58()
  // const xprv = m.derivePath("m/44'/144'/0'").toBase58()
  // const xpub = m.derivePath("m/44'/144'/0'").neutered().toBase58()
  const address = m.derivePath("m/44'/144'/0'/0/0").getAddress()
  // const {publicKey, privateKey} = m.derivePath("m/44'/144'/0'/0/0").keyPair.getKeyPairs()
  return {
    mnemonic,
    // seed,
    // masterSeed,
    // xprv,
    // xpub,
    address,
    // publicKey,
    // privateKey
  }
}

/**
 * 读取mnemonic, 批量获取地址，并写入result.json
 */
const getAccountInfoByMnemonic = () => {
  try {
    const sourceData = fs.readFileSync('./mnemonic.json', 'utf-8') // 读取mnemonic.json文件
    const mnemonicList = JSON.parse(sourceData)
    const arr = []
    const len = mnemonicList.length
    for(let i = 0; i < len; i++) {
        console.time('耗费')
        console.log(`正在获取第${i + 1}个助记词的地址`)
        const result = generateAccountByMnemonic(mnemonicList[i].mnemonic)
        console.timeEnd('耗费')
        console.log(`第${i + 1}个获取完成`)
        arr.push(result)
    }
    console.log('正在写入')
    fs.writeFileSync('./result.json', JSON.stringify(arr), 'utf-8')
    console.log('写入result.json完成')
  } catch (e) {
    console.log(e)
  }
}
// generateMnemonicList(1000)  // 如果没有mnemonic.json，将手动生成一个20w数据的助记词json

getAccountInfoByMnemonic()